﻿using Microsoft.Extensions.DependencyInjection;
using Modules.System.User;
using PetaPoco;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Caching;
using PmSoft.DBContext;
using PmSoft.Entity;
using PmSoft.Repositories;
using PmSoft.Utilities;


namespace Modules.System.EarlyWarning;

/// <summary>
/// 预警记录表仓储
/// </summary>
[UseDI(ServiceLifetime.Scoped)]
public class SysEarlyWarningRepository : Repository<SysEarlyWarning, DefaultDbContext>
{
    private readonly IApplicationContext applicationContext;
    public SysEarlyWarningRepository(DefaultDbContext dbContext, IApplicationContext applicationContext) : base(dbContext, applicationContext)
    {
        this.applicationContext = applicationContext;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="query"></param>
    /// <param name="pageIndex"></param>
    /// <param name="pageSize"></param>
    /// <returns></returns>
    public IPagedList<SysEarlyWarning> GetSysEarlyWarnings(SysEarlyWarningQuery query, int pageIndex, int pageSize)
    {
        Sql sql = Sql.Builder;
        sql.Select("sys_early_warning.id")
            .From("sys_early_warning");
        #region 主管单位数据权限
        if (applicationContext.CurrentUser is IDeptUser deptUser && !deptUser.IsSuperAdministrator())
        {
            sql.InnerJoin("project as prj").On($"sys_early_warning.object_id=prj.project_id and prj.is_deleted=0 and prj.industry_type=@0 ", deptUser.IndustryType);
            if (deptUser.Level == AdministrativeLevel.City)
                sql.Append($" and prj.city_code={deptUser.CityCode}");
            if (deptUser.Level == AdministrativeLevel.Area)
                sql.Append($" and prj.area_code={deptUser.AreaCode}");
        }
        #endregion
        switch (query.tenant)
        {
            case 预警租户.Project:
                sql.InnerJoin("project as b ").On("sys_early_warning.project_id=b.project_id");
                if (!string.IsNullOrEmpty(query.Keywords))
                    sql.Where("(b.name like @0)", "%" + StringUtility.StripSQLInjection(query.Keywords) + "%");
                break;
            default:
                break;
        }
        if (query.WarningType.HasValue)
            sql.Where("sys_early_warning.warning_type=@0", query.WarningType.Value);
        if (query.StartTime.HasValue)
            sql.Where("sys_early_warning.create_time>=@0", query.StartTime.Value);
        if (query.EndTime.HasValue)
            sql.Where("sys_early_warning.create_time<=@0", query.EndTime.Value);
        sql.OrderBy("sys_early_warning.create_time DESC");
        return GetPagingEntities(pageSize, pageIndex, sql);
    }
}